package cn.com.jdyun.util;


import cn.com.jdyun.exception.BdexGatewayException;
import cn.com.jdyun.pojo.User;
import cn.com.jdyun.util.reponse.Status;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.regex.Pattern;

public class WebConstants {

    public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    // 验证邮箱是否符合规定要求
    public static boolean validEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        boolean flag = false;

        Pattern pattern = Pattern.compile(str);
        flag = pattern.matcher(email).matches();

        return flag;
    }

    // 验证手机是否符合规定要求
    public static boolean validPhoneNumber(String mobile) {
        String str = "^((13[0-9])|(15[^4,\\D])|(14[57])|(17[0-9])|(18[0,0-9]))\\d{8}$";
        boolean flag = false;

        Pattern pattern = Pattern.compile(str);
        flag = pattern.matcher(mobile).matches();

        return flag;
    }

    public static boolean validIDCardNo(String idCardNo) {
        String str = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
        boolean flag = false;

        Pattern pattern = Pattern.compile(str);
        flag = pattern.matcher(idCardNo).matches();

        return flag;
    }


    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
     *
     * @return ip
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static void validCaptcha(String captcha, HttpSession session) throws BdexGatewayException {
        //判断验证码是否正确
        Object sessionCaptcha = session.getAttribute(Constant.CAPTCHA);
        session.removeAttribute(Constant.CAPTCHA);
        if (sessionCaptcha == null || !sessionCaptcha.toString().equalsIgnoreCase(captcha)) {
            throw new BdexGatewayException("图形验证码错误", Status.CAPTCHA_CODE_ERROR.getCode());
        }
    }

    public static void validEmailOrTelphone(String userVertifyInfo, String code, HttpSession session, User account) throws BdexGatewayException, UnsupportedEncodingException {
        //判断用户名和验证码是否对应
        Object sessionUsername = null,
                sessionCode = null;
        Long sessionSendTime = (Long)session.getAttribute(Constant.CODE_SEND_TIME);
        //判断验证码是否在有效期之内
        if (sessionSendTime != null && sessionSendTime !=0) {
            Long sendTime = sessionSendTime;
            long diff = System.currentTimeMillis() - sendTime;
            if (diff >= Constant.CODE_HOLD_TIME) {
                throw new BdexGatewayException("验证码已时效", Status.CODE_EXPIRED.getCode());
            }
        } else {
            throw new BdexGatewayException("The verification code has expired", Status.CODE_EXPIRED.getCode());
        }
        if (WebConstants.validEmail(userVertifyInfo)) {
            sessionUsername = session.getAttribute(Constant.EMAIL);
            sessionCode = session.getAttribute(Constant.EMAIL_CODE);
            session.removeAttribute(Constant.EMAIL);
            session.removeAttribute(Constant.EMAIL_CODE);
            if (sessionUsername == null || !sessionUsername.equals(userVertifyInfo) || sessionCode == null || !sessionCode.toString().equalsIgnoreCase(code)) {
                throw new BdexGatewayException("邮箱验证码错误", Status.CODE_ERROR.getCode());
            }
            if (account != null) {
                account.setEmail(userVertifyInfo);
            }
        } else if (WebConstants.validPhoneNumber(userVertifyInfo)) {
            sessionUsername = session.getAttribute(Constant.PHONE_NUMBER);
            sessionCode = session.getAttribute(Constant.PHONE_NUMBER_CODE);
            session.removeAttribute(Constant.PHONE_NUMBER);
            session.removeAttribute(Constant.PHONE_NUMBER_CODE);
            if (sessionUsername == null || !sessionUsername.equals(userVertifyInfo) || sessionCode == null || !sessionCode.toString().equalsIgnoreCase(code)) {
                throw new BdexGatewayException("手机验证码错误", Status.CODE_ERROR.getCode());
            }
            if (account != null) {
                account.setPhone(userVertifyInfo);
            }
        } else {
            throw new BdexGatewayException("用户名验证失败", Status.ACCOUNT_NAME_ERROR.getCode());
        }
    }

    public static String shadowUserName(String source) {
        if (source != null) {
            if (WebConstants.validEmail(source)) {
                int index = source.indexOf("@");
                if (index > 6) {
                    return source.substring(0, 3) + "***" + source.substring(6);
                }
            } else if (WebConstants.validPhoneNumber(source)) {
                return source.substring(0, 3) + "****" + source.substring(7, 11);
            }
        }
        return source;
    }

    public static String shadowIdCardName(String source) {
        if (source != null) {
            return source.substring(0, 6) + "********" + source.substring(14, 18);
        }
        return null;
    }

    public static String numberFormat(String pattern, String value) {
        DecimalFormat df = null;
        df = new DecimalFormat(pattern);
        if (StringUtils.isBlank(value)) {
            value = "0";
        }
        System.out.println(">> value:" + value);
        return df.format(Double.valueOf(value));
    }
}
